<template>
  <el-dialog title="检查项配置" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="700px" @closed="$refs.form.resetFields()">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
      <el-form-item prop="versionId" class="hide" />
      <el-form-item prop="versionCode" class="hide" />
      <el-form-item prop="cfgId" class="hide" />
      <el-form-item label="检查项" prop="chkitemCode">{{ form.chkitemCode }} - {{ form.chkitemName }}</el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="检查项类型" prop="chkitemType">
            <el-select v-model="form.chkitemType" placeholder="请选择检查项类型" style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_chkitem_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否启用" prop="isEnable"><el-switch v-model="form.isEnable" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否删除" prop="isDelete"><el-switch v-model="form.isDelete" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="数据类型" prop="dataType" :rules="isCqEval ? rules.dataType : []">
            <el-select v-model="form.dataType" placeholder="请选择数据类型" clearable style="width: 100%" @change="dataTypeChange">
              <el-option v-for="dict in dict.type.cq_eval_data_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="得分类型" prop="scoreType" :rules="isCqEval ? rules.scoreType : []">
            <el-select v-model="form.scoreType" placeholder="请选择得分类型" clearable style="width: 100%">
              <el-option v-for="dict in scoreTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="等级标准" prop="levelStdd">
            <el-select v-model="form.levelStdd" placeholder="请选择等级标准" clearable style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_level_std" :key="dict.value" :label="dict.label" :value="dict.raw.remark" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合格标准" prop="resultStdd">
            <el-select v-model="form.resultStdd" placeholder="请选择合格标准" clearable style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_reasult_std" :key="dict.value" :label="dict.label" :value="dict.raw.remark" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider class="f-title" content-position="left">业务信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属业务" prop="bussBelong" :rules="isChkitemType ? rules.bussBelong : []">
            <el-select v-model="form.bussBelong" placeholder="请选择所属业务" clearable style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_buss_belong" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检查单位" prop="rdcType">
            <el-select v-model="rdcTypeSelect" placeholder="请选择检查单位" multiple collapse-tags style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_rdc_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="装修类型" prop="decorationType">
            <el-select v-model="form.decorationType" placeholder="请选择检查单位" collapse-tags style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_delivery_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操盘类型" prop="tradeType">
            <el-select v-model="tradeTypeSelect" placeholder="请选择操盘类型" multiple collapse-tags style="width: 100%">
              <el-option v-for="dict in dict.type.cq_trade_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="录入方式" prop="inputMode" :rules="isCqEval ? rules.inputMode : []">
            <el-select v-model="form.inputMode" placeholder="请选择录入方式" clearable style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_input_mode" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="加减分对象" prop="addsubObj">
            <el-select v-model="addsubObjSelect" placeholder="请选择加减分对象" multiple collapse-tags style="width: 100%">
              <el-option v-for="dict in dict.type.cq_eval_addsub_obj" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="特殊规则" prop="specialRule">
            <el-select v-model="form.specialRule" placeholder="用于业务逻辑特殊判断使用" clearable filterable allow-create style="width: 100%">
              <el-option v-for="item in specialRuleList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="permCode" :rules="isCqEval || isCqHistory ? rules.permCode : []">
            <span slot="label">
              权限编码
              <el-tooltip placement="top" effect="light">
                <div slot="content" style="white-space: pre-line">{{ permCodeTip }}</div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-input v-model.trim="form.permCode" placeholder="请输入权限编码" :maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="icon">
            <span slot="label">
              图标
              <el-tooltip placement="top" effect="light" content="点击已选图标可选择颜色">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-color-picker class="color-picker" v-model="form.iconColor" v-show="form.icon" />
            <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
              <IconSelect ref="iconSelect" @selected="form.icon = $event" />
              <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" clearable @clear="form.iconColor = ''">
                <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" class="el-input__icon" style="height: 32px; width: 16px" :style="{ color: form.iconColor || '' }" />
                <i v-else slot="prefix" class="el-icon-search el-input__icon" />
              </el-input>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用品质规则" prop="qualityRuleType"><el-switch v-model="form.qualityRuleType" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用业态" prop="isProductType"><el-switch v-model="form.isProductType" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="默认值" prop="defaultJson"><el-input v-model="form.defaultJson" type="textarea" placeholder="JSON 格式，如：{&quot;score&quot;:&quot;10&quot;}" :maxlength="500" /></el-form-item>
      <el-form-item label="备注" prop="remark"><el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :maxlength="255" /></el-form-item>

      <el-divider class="f-title" content-position="left">统计信息</el-divider>
      <el-row>
        <el-col :span="6">
          <el-form-item label="事业部统计" prop="isBussCount"><el-switch v-model="form.isBussCount" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="城市公司统计" prop="isCityCount"><el-switch v-model="form.isCityCount" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目统计" prop="isProjectCount"><el-switch v-model="form.isProjectCount" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="合格项计算" prop="isValidCount"><el-switch v-model="form.isValidCount" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="优秀项计算" prop="isExceCount"><el-switch v-model="form.isExceCount" :active-value="1" :inactive-value="0" /></el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 添加或修改检查项配置
import { CQ_EVAL_CHKITEM_TYPE as CHKITEM_TYPE, CQ_EVAL_BUSS_BELONG as BUSS_BELONG } from '@/utils/baseData'
import { nameRule } from '@/utils/validate'
import { editFormMixin } from '@/utils/mixin'
import IconSelect from '@/components/IconSelect'
import { cpnKeys as specialRuleList } from '@/views/checkScore/specialRule'
import { listChkitemCfg, addChkitemCfg } from '@/api/checkScore/cqEval'
const filteredFields = ['versionId', 'versionCode', 'chkitemCode', 'chkitemName']

const permCodeTip = `用于配置页面权限，若权限编码设为“chkitem”，
则可在“系统管理→菜单管理”配置对应的操作权限：
列表 cq:eval:chkitem:list
新增 cq:eval:chkitem:add
编辑 cq:eval:chkitem:edit
删除 cq:eval:chkitem:remove
详情 cq:eval:chkitem:info
启用 cq:eval:chkitem:enable
禁用 cq:eval:chkitem:disable
导出 cq:eval:chkitem:export
注：需遵循 cq:eval:<权限编码>:<ACTION> 格式`

export default {
  components: { IconSelect },
  mixins: [editFormMixin],
  dicts: ['cq_eval_data_type', 'cq_eval_score_type', 'cq_eval_chkitem_type', 'cq_eval_buss_belong', 'cq_eval_level_std', 'cq_eval_reasult_std', 'cq_eval_rdc_type', 'cq_eval_delivery_type', 'cq_eval_addsub_obj', 'cq_eval_input_mode', 'cq_trade_type'],
  data() {
    return {
      specialRuleList,
      permCodeTip,
      primaryKey: 'cfgId',
      addApi: addChkitemCfg,
      form: {
        versionId: '',
        versionCode: '',
        decorationType:'',
        cfgId: '',
        chkitemCode: '',
        chkitemName: '',
        dataType: '',
        scoreType: '',
        chkitemType: '',
        bussBelong: BUSS_BELONG.CQEVAL,
        levelStdd: '',
        resultStdd: '',
        permCode: '',
        rdcType: '',
        addsubObj: '',
        tradeType: '',
        inputMode: '',
        specialRule: '',
        icon: '',
        iconColor: '',
        qualityRuleType: '',
        defaultJson: '',
        remark: '',
        isEnable: 1,
        isDelete: 0,
        isBussCount: 0,
        isCityCount: 0,
        isProjectCount: 0,
        isValidCount: 0,
        isExceCount: 0
      },
      rules: {
        dataType: [{ required: true, message: '请选择数据类型' }],
        scoreType: [{ required: true, message: '请选择得分类型' }],
        chkitemType: [{ required: true, message: '请选择检查项类型' }],
        permCode: [{ required: true, message: '请输入权限编码' }, nameRule],
        bussBelong: [{ required: true, message: '请选择所属业务' }],
        inputMode: [{ required: true, message: '请选择录入方式' }],
        specialRule: [nameRule]
      },
      currItem: {}
    }
  },
  computed: {
    scoreTypeList() {
      // 根据不同的数据类型，展示对应的得分类型
      const { dataType } = this.form
      const list = this.dict?.type.cq_eval_score_type || []
      if (!dataType) return list
      return list.filter(i => i.raw?.remark === dataType)
    },
    isChkitemType() {
      // 检查项类型为“检查项分类”
      return this.form.chkitemType === CHKITEM_TYPE.CHKITEMTYPE
    },
    isCqEval() {
      // 为检查项得分录入
      return this.isChkitemType && this.form.bussBelong === BUSS_BELONG.CQEVAL
    },
    isCqHistory() {
      // 为历史版本得分录入
      return this.isChkitemType && this.form.bussBelong === BUSS_BELONG.CQHISTORY
    },
    rdcTypeSelect: {
      get() {
        const str = this.form.rdcType || ''
        return str.split(',').filter(i => i)
      },
      set(val) {
        this.form.rdcType = val.join(',')
      }
    },

    addsubObjSelect: {
      get() {
        const str = this.form.addsubObj || ''
        return str.split(',').filter(i => i)
      },
      set(val) {
        this.form.addsubObj = val.join(',')
      }
    },
    tradeTypeSelect: {
      get() {
        const str = this.form.tradeType || ''
        return str.split(',').filter(i => i)
      },
      set(val) {
        this.form.tradeType = val.join(',')
      }
    }
  },
  methods: {
    open(item = {}) {
      this.show = true
      this.currItem = item
      this.$nextTick(() => this.getChkitemCfg())
    },
    async getChkitemCfg() {
      const { form, currItem } = this
      const versionId = currItem.itemVersionId
      const versionCode = currItem.itemVersionCode
      const { chkitemCode } = currItem
      if (!versionCode) return this.msgError('参数错误：版本号不能为空')
      if (!chkitemCode) return this.msgError('参数错误：检查项编码不能为空')

      filteredFields.map(k => (form[k] = currItem[k]))
      form.versionId = versionId
      form.versionCode = versionCode

      this.listLoading = true
      const opt = { versionCode, chkitemCode }
      const res = await listChkitemCfg(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.data?.[0] || {}
      Object.keys(form)
        .filter(k => !filteredFields.includes(k))
        .map(k => (form[k] = typeof data[k] !== 'undefined' && data[k] !== null ? data[k] : this.formInitVals[k]))

      // 移除id，总执行新增
      form.cfgId = ''
    },
    // 数据类型切换
    dataTypeChange(val) {
      if (!val) return
      const list = this.scoreTypeList
      this.form.scoreType = list[0]?.value || ''
    }
  }
}
</script>
<style scoped lang="scss">
.color-picker {
  position: absolute;
  z-index: 1;
  opacity: 0;
}
.f-title {
  .el-divider__text {
    color: #409eff;
    font-weight: bold;
  }
}
</style>
